package com.wangtao.rpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable{

    //Channel上下文
    private ChannelHandlerContext context;
    //发送的参数
    private String params;
    //返回的结果
    private String result;


    //当通道准备就绪时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //赋值上下文对象
        context = ctx;
    }

    //当有数据读取时
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //读取服务端发来的数据
        result = msg.toString();
        notify(); //随机唤醒一个线程
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //有异常发送关闭通道
        System.out.println(cause.getMessage());
        ctx.close();
    }

    @Override
    public synchronized Object call() throws Exception {
        //向服务端发送数据
        context.writeAndFlush(params);
        //阻塞当前线程
        wait();
        //返回结果
        return result;
    }

    void setParams(String params) {
        this.params = params;
    }
}
